import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { RouteLocationNormalized } from 'vue-router'

export interface TagView {
  path: string
  title: string
  name?: string
  fullPath?: string
}

export const useTagsStore = defineStore('tags', () => {
  const visitedViews = ref<TagView[]>([
    { path: '/', title: '首页' }
  ])

  const addView = (view: RouteLocationNormalized) => {
    if (!view.meta?.title) return
    const isExist = visitedViews.value.some(v => v.path === view.path)
    if (!isExist) {
      visitedViews.value.push({
        path: view.path,
        title: view.meta.title as string,
        name: view.name as string,
        fullPath: view.fullPath
      })
    }
  }

  const delView = (view: TagView) => {
    const index = visitedViews.value.indexOf(view)
    if (index > -1) {
      visitedViews.value.splice(index, 1)
    }
    return [...visitedViews.value]
  }

  const delOthersViews = (view: TagView) => {
    visitedViews.value = visitedViews.value.filter(v => {
      return v.path === view.path || v.path === '/'
    })
    return [...visitedViews.value]
  }

  const delAllViews = () => {
    visitedViews.value = visitedViews.value.filter(v => v.path === '/')
    return [...visitedViews.value]
  }

  const sortTags = (oldIndex: number, newIndex: number) => {
    if (oldIndex === 0 || newIndex === 0) return // 不允许移动首页标签
    const itemToMove = visitedViews.value[oldIndex]
    visitedViews.value.splice(oldIndex, 1)
    visitedViews.value.splice(newIndex, 0, itemToMove)
  }

  return {
    visitedViews,
    addView,
    delView,
    delOthersViews,
    delAllViews,
    sortTags
  }
}) 